const sql = require('mssql');

let connections = {};

exports.use = function (database) {
  const config = {
    user: 'sa',
    port: '1433',
    password: 'ZyMk$$$2017',
    server: '172.16.7.20',
    database: database || 'manke',
    pool: {
      max: 10,
      min: 0,
      idleTimeoutMillis: 30000
    }
  };
  // console.log(`already connected ${Object.keys(connections).join(',')}`)
  const promise = new Promise((resolve, reject) => {
    const database = config.database;
    let conn = connections[database];
    if (!conn) {
      conn = connections[database] = {
        pool: new sql.ConnectionPool(config)
      };
      conn.promise = conn.pool.connect()
    }
    // console.log(`conn connected=${conn.pool.connected} connecting=${conn.pool.connecting}`)
    if (conn.pool.connected) {
      // console.log(`use new connection ${database}`)
      // console.timeEnd('conn')
      resolve(conn.pool)
    } else if (conn.pool.connecting) {
      // console.log(`use new connection ${database}`)
      conn.promise.then(() => {
        // console.timeEnd('conn')
        resolve(conn.pool)
      })
    }
  });

  return {
    query: function (sql, inputs) {
      return promise.then((conn) => {
        // console.time('query')
        let chain = conn.request();
        if (inputs) {
          for (let i in inputs) {
            if (inputs.hasOwnProperty(i)) {
              chain = chain.input(i, inputs[i])
            }
          }
        }
        const result = chain.query(sql);
        // console.timeEnd('query')
        return result
      })
    },
    execute: function (store, inputs) {
      return promise.then((conn) => {
        let chain = conn.request();
        if (inputs) {
          for (let i in inputs) {
            if (inputs.hasOwnProperty(i)) {
              chain = chain.input(i, inputs[i])
            }
          }
        }
        const result = chain.query(store);
        return result
      })
    }
  }
};

function closeConn(database) {
  let conn = connections[database];
  if (conn) {
    delete connections[database];
    console.log(database + ':' + conn.pool.config.database);
    if (conn.pool.connected) {
      console.log(`close connected ${database}`)
      conn.pool.close()
    } else if (conn.pool.connecting) {
      console.log(`close connecting ${database}`)
      // conn.promise.then(() => conn.pool.close())
    }
  }
}

let closeTimer;

exports.close = function () {
  let args = arguments;
  if (closeTimer) {
    clearTimeout(closeTimer);
    closeTimer = null
  }
  closeTimer = setTimeout(() => {
    if (args.length) {
      let names = Array.prototype.slice.call(args, 0);
      names.forEach(closeConn)
    } else {
      for (let i in connections) {
        closeConn(i)
      }
    }
  }, 3000)
}
